#!/usr/bin/env node

import { LocalRepository } from './dist/local-repository.js';
import { ClassFinder } from './dist/class-finder.js';
import { JavaDecompiler } from './dist/decompiler.js';

console.log('🔍 AuditDomain 完整反编译测试');
console.log('='.repeat(60));

async function testAuditDomainDecompilation() {
  // Load environment variables
  const CFR_PATH = process.env.CFR_PATH || './tools/cfr.jar';
  const MAVEN_LOCAL_REPOSITORY = process.env.MAVEN_LOCAL_REPOSITORY || '/mnt/d/mavenrepository';
  
  console.log(`📁 Maven仓库路径: ${MAVEN_LOCAL_REPOSITORY}`);
  console.log(`🔧 CFR路径: ${CFR_PATH}`);
  
  const classFinder = new ClassFinder();
  const localRepository = new LocalRepository(classFinder);
  const decompiler = new JavaDecompiler();
  
  // Set the repository path
  localRepository.setLocalRepositoryPath(MAVEN_LOCAL_REPOSITORY);
  
  try {
    console.log('\n🔍 扫描本地Maven仓库...');
    const allArtifacts = await localRepository.scanLocalRepository();
    console.log(`✅ 找到 ${allArtifacts.length} 个artifacts`);
    
    // Find artifacts containing AuditDomain
    console.log('\n🎯 查找包含AuditDomain的artifacts...');
    const targetArtifacts = allArtifacts.filter(artifact => 
      artifact.artifactId.includes('hzero-boot-customize') ||
      artifact.artifactId.includes('hzero-starter-mybatis-mapper')
    );
    
    console.log(`找到 ${targetArtifacts.length} 个目标artifacts:`);
    targetArtifacts.forEach((artifact, index) => {
      console.log(`  ${index + 1}. ${artifact.groupId}:${artifact.artifactId}:${artifact.version}`);
    });
    
    for (const [index, artifact] of targetArtifacts.entries()) {
      console.log(`\n${'='.repeat(80)}`);
      console.log(`📦 分析 Artifact ${index + 1}:`);
      console.log(`   ${artifact.groupId}:${artifact.artifactId}:${artifact.version}`);
      console.log(`   路径: ${artifact.localPath}`);
      console.log(`${'='.repeat(80)}`);
      
      try {
        const classes = await localRepository.getLocalArtifactClasses(artifact);
        console.log(`📋 该artifact包含 ${classes.length} 个类`);
        
        const auditDomainClasses = classes.filter(cls => 
          cls.fullName.includes('AuditDomain')
        );
        
        if (auditDomainClasses.length > 0) {
          console.log(`✅ 找到 ${auditDomainClasses.length} 个AuditDomain类:`);
          
          for (const cls of auditDomainClasses) {
            console.log(`\n🎯 反编译类: ${cls.fullName}`);
            console.log(`   包名: ${cls.packageName}`);
            console.log(`   类名: ${cls.className}`);
            
            try {
              // Extract class bytecode
              const classBytes = await classFinder.getClassSource(cls);
              if (classBytes) {
                console.log(`   字节码大小: ${classBytes.length} bytes`);
                
                // Decompile with CFR
                console.log(`\n🔧 开始反编译...`);
                const decompileResult = await decompiler.decompileClass(classBytes, cls.fullName);
                
                if (decompileResult.success) {
                  console.log(`✅ 反编译成功！`);
                  console.log(`\n${'📄 JAVA 源代码'.padStart(40, ' ')}`);
                  console.log(`${'='.repeat(80)}`);
                  console.log(decompileResult.source);
                  console.log(`${'='.repeat(80)}`);
                  
                  // Save to file for easy viewing
                  const fileName = `./AuditDomain_${artifact.artifactId}_${artifact.version.replace(/[\/\\:*?"<>|]/g, '-')}.java`;
                  const fs = await import('fs/promises');
                  await fs.writeFile(fileName, decompileResult.source);
                  console.log(`💾 源代码已保存到: ${fileName}`);
                  
                } else {
                  console.log(`❌ 反编译失败: ${decompileResult.error}`);
                }
              } else {
                console.log(`❌ 无法提取类字节码`);
              }
            } catch (error) {
              console.error(`❌ 反编译过程出错: ${error.message}`);
            }
            
            console.log(`\n${'-'.repeat(60)}`);
          }
        } else {
          console.log(`❌ 该artifact中未找到AuditDomain类`);
        }
      } catch (error) {
        console.error(`❌ 分析artifact时出错: ${error.message}`);
      }
    }
    
    console.log(`\n🎉 测试完成！`);
    console.log(`💡 如果看到了完整的Java源代码，说明反编译功能工作正常`);
    
  } catch (error) {
    console.error('❌ 测试失败:', error);
  }
}

// Load environment variables from .env file
try {
  const fs = await import('fs/promises');
  const envContent = await fs.readFile('.env', 'utf-8');
  const envVars = envContent
    .split('\n')
    .filter(line => line.trim() && !line.startsWith('#'))
    .reduce((vars, line) => {
      const [key, value] = line.split('=');
      if (key && value) {
        vars[key.trim()] = value.trim().replace(/^["'](.*)["']$/, '$1');
      }
      return vars;
    }, {});
  
  Object.assign(process.env, envVars);
} catch (error) {
  console.log('⚠️  无法加载.env文件，使用默认配置');
}

testAuditDomainDecompilation();